package com.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jwt.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Objects;

@Slf4j
public class JwtUtil {

    private static final String KEYS = "eyJzdWIiOiLkvZnmmbrli4ciLCJleHAiOjE2NzkwNDM0MjcsInVzZXJuYW1lIjoieXV6aGl5b25nIn0";

    /**
     * 生成token令牌
     *
     * @param userModel 用户信息
     * @return
     */
    public static String getToken(UserModel userModel) {
        if (Objects.isNull(userModel)) {
            throw new RuntimeException("登录参数不能为空");
        }
        Calendar currentTime = Calendar.getInstance();
        currentTime.add(Calendar.DATE, 7);

        String token = JWT.create().withClaim("userId", userModel.getId())
                .withClaim("username", userModel.getUsername())
                .withExpiresAt(currentTime.getTime())
                .withSubject("余智勇")
                .sign(getAlgorithm(KEYS));
        return token;
    }

    /**
     * 算法
     *
     * @param password
     * @return
     */
    private static Algorithm getAlgorithm(String password) {
        return Algorithm.HMAC256(password);
    }

    /**
     * 校验token的正确性
     *
     * @param token token令牌
     * @return
     */
    public static DecodedJWT verifyToken(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token不能为空");
        }

        // 获取登录用户真正的密码假如数据库查出来的是123456
        return JWT.require(getAlgorithm(KEYS)).build().verify(token);
    }

    public static void main(String[] args) {
//        UserModel userModel = new UserModel();
//        userModel.setUsername("yuzhiyong");
//        userModel.setPassword("1223");
//        String token = getToken(userModel);
//        System.out.println(token);
//
//        DecodedJWT decodedJWT = verifyToken(token);
//        System.out.println("-------" + decodedJWT.getHeader() + "---" + decodedJWT.getPayload() + "---" + decodedJWT.getSignature());
//
//        Map<String, Claim> claims = decodedJWT.getClaims();
//        System.out.println(claims);

//        byte[] encode = Base64Utils.decode("eyJzdWIiOiLkvZnmmbrli4ciLCJleHAiOjE2NzkwMzg2NjIsInVzZXJuYW1lIjoieXV6aGl5b25nIn0".getBytes());
//        String s = new String(encode);
//        System.out.println(s);
    }
}
